import * as THREE from "three";
import * as d3 from "d3";
import scene from "./scene";
import FlyLineShader from "./mesh/FlyLineShader"
import {ScaleLinear} from "./index"
import starVertexShader from "@/shader/star/vertex.glsl?raw";
import starFragmentShader from "@/shader/star/fragment.glsl?raw";

// 加载纹理
const map = new THREE.Object3D();
// 导入纹理
const textureLoader = new THREE.TextureLoader();
const texture = textureLoader.load("textures/star.png");
// const heilongjiangTexture = textureLoader.load("textures/heilongjiang.png");
// const changchunTexture = textureLoader.load("textures/changchun.png");
// const kucheTexture = textureLoader.load("textures/kuche.png");
// const shacheTexture = textureLoader.load("textures/shache.png");
// const ningboTexture = textureLoader.load("textures/ningbo.png");

// 以经纬度116，39为中心，进行投影的函数转换函数
const projection1 = d3.geoMercator().center([116, 39]).translate([0, 0, 0]);

export  function jsonLoader() {
  const loader = new THREE.FileLoader();
  loader.load("./json/CHINA.json", (data) => {
    const jsonData = JSON.parse(data);
    operationData(jsonData);
  });
}

function operationData(jsondata) {
  // 全国信息
  const features = jsondata.features;

  features.forEach((feature) => {
    // 单个省份 对象
    const province = new THREE.Object3D();
    // 地址
    province.properties = feature.properties.name;
    // 地点的code
    province.adcode = feature.properties.adcode;
    const coordinates = feature.geometry.coordinates;
    let color = "#1e80ff";
    if ([230000, 220000, 650000, 330000, 210000].includes(Number(province.adcode))) {
      color = "#90c890";
    }
    if (feature.geometry.type === "MultiPolygon") {
      // 多个，多边形
      coordinates.forEach((coordinate) => {
        // coordinate 多边形数据
        coordinate.forEach((rows) => {
          const mesh = drawExtrudeMesh(rows, color, projection1);
          const line = lineDraw(rows, color, projection1);
          // 唯一标识
          mesh.properties = feature.properties.name;

          province.add(line);
          province.add(mesh);
        });
      });
    }

    if (feature.geometry.type === "Polygon") {
      // 多边形
      coordinates.forEach((coordinate) => {
        const mesh = drawExtrudeMesh(coordinate, color, projection1);
        const line = lineDraw(coordinate, color, projection1);
        // 唯一标识
        mesh.properties = feature.properties.name;

        province.add(line);
        province.add(mesh);
      });
    }
    /**
     * 如果是有公司分布的省份，进行标记
     * 1.浙江(宁波，经纬度(121.84431,29.89889))
     * 2.辽宁(沈阳，经纬度(123.46987,41.80515))
     * 3.吉林(长春,经纬度(125.28845,43.83327))
     * 4.黑龙江(密山，131.84631,45.52975)
     * 5.新疆(喀什，39.47042,75.98976  库车，41.71741,82.96212)
     */
    map.add(province);
  });
  const pointColor = "#f64242";
      const positionPointList = {
        宁波: [121.84431, 29.89889],
        沈阳: [123.46987, 41.80515],
        长春: [125.28845, 43.83327],
        密山: [131.84631, 45.52975],
        喀什: [75.98976, 39.47042],
        库车: [82.96212, 41.71741],
      };
      Object.values(positionPointList).forEach((row) => {
        const point = pointDraw(row, pointColor, projection1);
        map.add(point);
    });
  drawFlyLine(projection1);
  scene.add(map);
}

// 根据经纬度坐标生成star
function pointDraw(point, color, projection) {
  // 创建一个几何体
  const [x, y] = projection(point);
  const group= new THREE.Object3D();
  let spriteMaterial = new THREE.SpriteMaterial( { map: texture, color: new THREE.Color(color) } );
   // 添加标点
  const sprite1 = new THREE.Sprite( spriteMaterial );
  sprite1.position.set(x, -y, 11);
  sprite1.scale.set(3, 3, 2);
  // let spriteMaterial1 = new THREE.SpriteMaterial( { map: heilongjiangTexture } );
  // const sprite2 = new THREE.Sprite( spriteMaterial1 );
  // sprite2.position.set(x+25,-y,15);
  // sprite2.scale.set(10, 10, 2);
  // group.add(sprite2);
  group.add(sprite1);
  return group
//   const pointsArray = new Array();
//   // 创建三维点
//   pointsArray.push(new THREE.Vector3(x, -y, 11));
//   const rotationMatrix = new THREE.Matrix4().makeRotationY(Math.PI); // 90 degrees in radians
//   geometry.setFromPoints(pointsArray);
//   // 设置点的着色器材质
//   const material = new THREE.ShaderMaterial({
//     vertexShader: starVertexShader,
//     fragmentShader: starFragmentShader,
//     uniforms: {
//       uTexture: {
//         value: texture,
//       },
//       vColor: {
//         value: new THREE.Color(color),
//       },
//       rotationMatrix: { value: rotationMatrix },
//     },
//     side: "DoubleSide",
//     depthWrite: false,
//     transparent: true,
//   });

//   // 创建网格对象并添加到场景中
//   const star = new THREE.Points(geometry, material);
  // 创建一个点云
//   return star;
}

// 创建飞线
export function drawFlyLine(projection) {
    const [baseX,baseY]= projection([121.84431, 29.89889]);
    const basePosition= {
        x:baseX,
        y:-baseY
    }
    // 将数据进行微调
    const positionPointList = {
        // 宁波: [121.84431, 29.89889],
        沈阳: [124.5, 41.80515],
        长春: [127, 44],
        密山: [134, 46],
        喀什: [70.5, 39.47042],
        库车: [78.5, 41.71741],
    };
    Object.values(positionPointList).forEach((row) => {
         //   生成随机颜色
        const color = new THREE.Color(
            Math.random(),
            Math.random(),
            Math.random()
        ).getHex();
        // 这里是地图上的x，y，我需要得到在场景中的x,y
        const [x, y] = projection(row);
        const position= {
            x:x,
            y:-y,
            z: 80
        }
        // 添加着色器飞线
        const flyLineShader = new FlyLineShader(basePosition,position, color);
        scene.add(flyLineShader.mesh);
    })
   
}

function lineDraw(polygon, color, projection) {
  const lineGeometry = new THREE.BufferGeometry();
  const pointsArray = new Array();
  polygon.forEach((row) => {
    const [x, y] = projection(row);
    // 创建三维点
    pointsArray.push(new THREE.Vector3(x, -y, 9));
  });
  // 放入多个点
  lineGeometry.setFromPoints(pointsArray);

  const lineMaterial = new THREE.LineBasicMaterial({
    color: color,
  });
  return new THREE.Line(lineGeometry, lineMaterial);
}

// 根据经纬度坐标生成物体
function drawExtrudeMesh(polygon, color, projection) {
  const shape = new THREE.Shape();
  polygon.forEach((row, i) => {
    const [x, y] = projection(row);
    if (i === 0) {
      shape.moveTo(x, -y);
    }
    shape.lineTo(x, -y);
  });

  // 拉伸
  const geometry = new THREE.ExtrudeGeometry(shape, {
    depth: 10,
    bevelEnabled: false,
  });
  const material = new THREE.MeshBasicMaterial({
    color: color,
    transparent: true,
    opacity: 0.5,
  });
  return new THREE.Mesh(geometry, material);
}
